<template>
  <div class="filter">
    <div v-if="leftSymbol" class="left symbol" @click="handlerClick">
      {{ leftSymbol }}
    </div>
    <div v-else class="left" @click="handlerClick">
      <img ref="img" :src="filterIcon" />
    </div>
    <div class="right">
      <input v-model="inputVal" @input="handlerInput" />
    </div>
  </div>
</template>
<script>
import filterIcon from './icons/filter-icon.png'

import filterHitIcon from './icons/filter-hit-icon.png'

export default {
  props: {
    currentTd: {
      type: Object,
      default: () => {}
    },

    showFilterPopover: {
      type: Function
    },

    filterPool: {
      type: Array,
      default: () => []
    },

    updateFilterPool: {
      type: Function
    }
  },

  watch: {
    filterPool: {
      handler() {
        const filterItem = this.filterPool.find(
          poolItem => poolItem.currentTd.id === this.currentTd.id
        )
        if (filterItem) {
          this.leftSymbol = filterItem.symbolData && filterItem.symbolData.symbol
          this.inputVal = filterItem.inputVal
        } else {
          this.leftSymbol = ''
        }
      },
      immediate: true,
      deep: true
    }
  },

  data() {
    return {
      leftSymbol: '',
      inputVal: '',
      filterIcon: filterIcon,
      filterHitIcon: filterHitIcon
    }
  },

  methods: {
    handlerClick() {
      const rect = this.$el.getBoundingClientRect()
      this.showFilterPopover({ rect, currentTd: this.currentTd })
    },

    handlerInput() {
      this.debounce(() => {
        this.updateFilterPool({ inputVal: this.inputVal, currentTd: this.currentTd })
      }, 300)()
    },

    // 函数防抖
    debounce(func, wait) {
      return () => {
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(func, wait)
      }
    }
  }
}
</script>
<style scoped>
.filter {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #fff;
  cursor: pointer;
}

.left {
  width: 40px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
}
.left img {
  width: 15px;
  height: 15px;
}

.symbol {
  color: #409eff;
}

.right {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  color: #1989fa;
}

.right input {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
}
</style>
